#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
超简单 Joycon 读取器
专注于基本的连接检测和读取功能

Author: Assistant
Date: 2024-12-19
"""

import pygame
import time
import sys

class UltraSimpleJoyconReader:
    """超简单 Joycon 读取器"""
    
    def __init__(self):
        self.joysticks = []
        self.connected = False
        
        # 初始化 pygame
        try:
            pygame.init()
            pygame.joystick.init()
            print("✅ pygame 初始化成功")
        except Exception as e:
            print(f"❌ pygame 初始化失败: {e}")
            return
    
    def scan_devices(self):
        """扫描手柄设备"""
        print("扫描手柄设备...")
        
        joystick_count = pygame.joystick.get_count()
        print(f"检测到 {joystick_count} 个手柄设备")
        
        if joystick_count == 0:
            print("❌ 未检测到任何手柄设备")
            print("可能的原因:")
            print("1. Joycon 未正确连接")
            print("2. 缺少必要的驱动程序")
            print("3. 系统未识别手柄")
            return False
        
        # 初始化所有手柄
        for i in range(joystick_count):
            try:
                joystick = pygame.joystick.Joystick(i)
                joystick.init()
                
                name = joystick.get_name()
                print(f"手柄 {i}: {name}")
                print(f"  轴数量: {joystick.get_numaxes()}")
                print(f"  按钮数量: {joystick.get_numbuttons()}")
                print(f"  帽子数量: {joystick.get_numhats()}")
                
                self.joysticks.append(joystick)
                
            except Exception as e:
                print(f"初始化手柄 {i} 失败: {e}")
        
        self.connected = len(self.joysticks) > 0
        return self.connected
    
    def read_inputs(self):
        """读取输入"""
        if not self.connected:
            return None
        
        # 处理 pygame 事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return None
        
        data = {
            'buttons': {},
            'axes': {},
            'hats': {},
            'connected': self.connected
        }
        
        # 读取每个手柄的输入
        for joystick_id, joystick in enumerate(self.joysticks):
            # 读取按钮
            for i in range(joystick.get_numbuttons()):
                button_pressed = joystick.get_button(i)
                if button_pressed:
                    data['buttons'][f'joycon_{joystick_id}_button_{i}'] = True
            
            # 读取摇杆轴
            for i in range(joystick.get_numaxes()):
                axis_value = joystick.get_axis(i)
                if abs(axis_value) > 0.1:  # 只记录有意义的输入
                    data['axes'][f'joycon_{joystick_id}_axis_{i}'] = axis_value
            
            # 读取帽子
            for i in range(joystick.get_numhats()):
                hat_value = joystick.get_hat(i)
                if hat_value != (0, 0):
                    data['hats'][f'joycon_{joystick_id}_hat_{i}'] = hat_value
        
        return data
    
    def print_status(self, data):
        """打印状态"""
        if not data:
            return False
        
        print("\n" + "="*50)
        print("Joycon 状态")
        print("="*50)
        
        if data['connected']:
            print("✅ 连接状态: 已连接")
        else:
            print("❌ 连接状态: 未连接")
            return False
        
        # 显示按钮状态
        if data['buttons']:
            print("🔘 按下的按钮:")
            for button, pressed in data['buttons'].items():
                if pressed:
                    print(f"  - {button}")
        else:
            print("🔘 按钮: 无按下")
        
        # 显示摇杆状态
        if data['axes']:
            print("🎮 摇杆输入:")
            for axis, value in data['axes'].items():
                print(f"  - {axis}: {value:.3f}")
        else:
            print("🎮 摇杆: 无输入")
        
        # 显示帽子状态
        if data['hats']:
            print("🎯 方向键:")
            for hat, value in data['hats'].items():
                print(f"  - {hat}: {value}")
        else:
            print("🎯 方向键: 无输入")
        
        return True
    
    def run(self, update_rate=5.0):
        """运行主循环"""
        print("超简单 Joycon 读取器")
        print("="*50)
        
        # 扫描设备
        if not self.scan_devices():
            print("\n故障排除建议:")
            print("1. 确保 Joycon 已通过蓝牙连接")
            print("2. 检查蓝牙是否已启用")
            print("3. 尝试重新配对手柄")
            print("4. 在 Linux 上运行:")
            print("   sudo modprobe hid-nintendo")
            print("   sudo modprobe hid-generic")
            print("5. 重启蓝牙服务:")
            print("   sudo systemctl restart bluetooth")
            return
        
        print("开始读取 Joycon 输入...")
        print("按 Ctrl+C 退出")
        
        try:
            while True:
                data = self.read_inputs()
                if not self.print_status(data):
                    break
                time.sleep(1.0 / update_rate)
                
        except KeyboardInterrupt:
            print("\n程序已退出")
        finally:
            pygame.quit()

def main():
    """主函数"""
    reader = UltraSimpleJoyconReader()
    reader.run()

if __name__ == "__main__":
    main() 